package com.freshfresh.activity.selfcenter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.freshfresh.activity.BaseActivity;
import com.freshfresh.activity.R;
import com.freshfresh.utils.FreshConstants;
import com.freshfresh.utils.UrlConstants;
import com.freshfresh.utils.Utils;
import com.freshfresh.view.db.DBManager;

public class LoginActivity extends BaseActivity implements OnClickListener{

	private Button btn_login;
	private TextView tv_register;
	private EditText ed_name;
	private EditText ed_pwd;
	private String userName;
	private long lastTime;
	private boolean fromUpdatePassword;
	private List<Map<String, Object>> listmap;
	Dialog progressDialog;
	TextView tv_ac_login_register;
	RelativeLayout rel_back;
	TextView tv_title;
	 List<Map<String,Object>> listmap_local;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_login);
		// setMyActivity(this);
		// Cache.add(this);

		fromUpdatePassword = getIntent().getBooleanExtra("fromUpdatePassword",
				false);
		
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_title.setText("登陆");
		rel_back = (RelativeLayout) findViewById(R.id.rel_back);
		tv_ac_login_register = (TextView) findViewById(R.id.tv_ac_login_register);
		btn_login = (Button) findViewById(R.id.btn_login);
		// btn_wechat_login = (Button) findViewById(R.id.btn_wechat_login);

		ed_name = (EditText) findViewById(R.id.ed_ac_login_user_name);
		ed_pwd = (EditText) findViewById(R.id.ed_ac_login_user_pwd);
		tv_register = (TextView) findViewById(R.id.tv_ac_login_register);

		btn_login.setOnClickListener(this);
		// btn_wechat_login.setOnClickListener(this);

		tv_register.setOnClickListener(this);
		tv_ac_login_register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
				startActivity(intent);
			}
		});
		rel_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				LoginActivity.this.finish();
			}
		});
		
		
		// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		// startActivity(intent);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onClick(View arg0) {
		Intent it = null;
		switch (arg0.getId()) {
		case R.id.btn_login:
			login();
			break;
		case R.id.tv_ac_login_register:
//			it = new Intent(LoginActivity.this, RegisterActivity.class);
//			startActivity(it);
			break;
		default:
			break;
		}
	}

	protected void login() {
		userName = ed_name.getText().toString();
		String pwd = ed_pwd.getText().toString();
		if (userName.equals("")) {
			showToast(LoginActivity.this, "请输入用户名");
			return;
		}
		if (pwd.equals("")) {
			showToast(LoginActivity.this, "请输入密码");
			return;
		}

		progressDialog = Utils
				.createLoadingDialog(LoginActivity.this, "正在登陆……");
		progressDialog.show();
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", userName);
		params.put("password", pwd);
		Log.e("username是多少………………", userName);
		Log.e("password是多少………………", pwd);
		Log.e("url是多少………………", UrlConstants.login_url);
		executeRequest(new StringRequest(UrlConstants.login_url, params,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						progressDialog.dismiss();
						Log.e("arg0是多少………………", arg0);
						if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
							String userid = Utils.parseJsonStr(arg0)
									.get("userid").toString();
							String token = Utils.parseJsonStr(arg0)
									.get("token").toString();

							SharedPreferences userShared = FreshConstants
									.getUserShared(LoginActivity.this);
							Editor editor = userShared.edit();
							editor.putString("userid", userid);
							editor.putString("token", token);
							editor.putString("mobile", ed_name.getText().toString());
							editor.commit();

							initShoppingCar();
							
							Intent intent=new Intent();
							setResult(201, intent);
							LoginActivity.this.finish();
							// finish();
							// // finish();
						} else {
							if (Utils.parseJsonStr(arg0).get("errorcode")
									.equals("Invalid login or password.")) {
								showToast(LoginActivity.this,
										"登录失败，用户名或密码错误，请重新输入");
							} else {
								showToast(LoginActivity.this, "登录失败，" + "请稍候再试");
							}
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {

					}
				}));
	}

//初始化购物车
	public void initShoppingCar(){
		
		listmap_local=new ArrayList<Map<String,Object>>();
		
		SharedPreferences share=FreshConstants.getUserShared(LoginActivity.this);
		final String userid=share.getString("userid", "");
		final String token=share.getString("token", "");
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("store", "1");
		params.put("quoteid", "");
		params.put("token", token);
		params.put("customerid", userid);
		String ad_url = UrlConstants.getShoppingCarInfo;
		Log.e("url是多少…………", ad_url);
		Log.e("token是多少…………", token);
		Log.e("userid是多少…………", userid);
		executeRequest(new StringRequest(ad_url, params,
				new Response.Listener<String>() {
					public void onResponse(String arg0) {
						progressDialog.dismiss();
						Log.e("listmap的……", arg0);
						if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
							Map<String,Object> map=(Map<String,Object>)Utils.parseJsonStr(arg0).get("data");
							String str_quoteid=map.get("quoteid").toString();
							SharedPreferences share=FreshConstants.getUserShared(LoginActivity.this);
							share.edit().putString("quoteid", str_quoteid).commit();
							List<Map<String,Object>> listmap_serve=(List<Map<String,Object>>)map.get("product_info");//我的服务器购物车
							
							Cursor cursor=getAllPersonInfo();
							if(cursor.moveToNext()){
								//本地有数据
								listmap_local=queryAllLocal();
								
								//同步本地购物车到服务器
								List<Map<String,Object>> listmap=new ArrayList<Map<String,Object>>();
								for(int j=0;j<listmap_local.size();j++){
									Map<String,Object> mapss=new HashMap<String, Object>();
									mapss.put("product_id", listmap_local.get(j).get("product_id").toString());
									mapss.put("bundle_id", "");
									mapss.put("qty", listmap_local.get(j).get("count").toString());
									listmap.add(mapss);
								}
								Log.e("listmap的长度是多少12380", listmap.size()+"");
								String strjson=JSON.toJSONString(listmap);
								Log.e("strjson是多少（（（（（（））））））", strjson);
								
								Map<String, String> params = new HashMap<String, String>();
								params.put("store", "1");
								params.put("quoteid", "");
								params.put("token", token);
								params.put("customerid", userid);
								params.put("productsdata", strjson);
								
								
								Map<String,Object> map_obj=new HashMap<String, Object>();
								map_obj.put("customerid", userid);
								map_obj.put("store ", "1");
								map_obj.put("token ", token);
								map_obj.put("productsdata ", strjson);
								String str_mapobj=Utils.map2json(map_obj);
								
								params.put("cartProductAdd", str_mapobj);
								
								String ad_url = UrlConstants.AddShoppingCar;
								executeRequest(new StringRequest(ad_url, params,
										new Response.Listener<String>() {
											public void onResponse(String arg0) {
												progressDialog.dismiss();
												Log.e("listmap的……", arg0);
												if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
													Map<String,Object> map=(Map<String,Object>)Utils.parseJsonStr(arg0).get("data");
													String quoteidstr=map.get("quoteid").toString();
													SharedPreferences share=FreshConstants.getUserShared(LoginActivity.this);
													share.edit().putString("quoteid", quoteidstr).commit();
													List<Map<String,Object>> listmap_serves=(List<Map<String,Object>>)map.get("product_info");
													//删除本地购物车
													 String sql = "DELETE FROM " + "fresh_shoppingcar" +";";
													 DBManager.getDBconnection(LoginActivity.this).execSQL(sql);
													 
													 Intent intent=new Intent(FreshConstants.UPDATELOCAL_SHOPPINGCAR);
														intent.putExtra("list", (Serializable)listmap_serves);
														context.sendBroadcast(intent);
												} 
											}

										}, new Response.ErrorListener() {

											public void onErrorResponse(VolleyError arg0) {
												progressDialog.dismiss();
												Toast.makeText(LoginActivity.this, "更新失败", 1).show();
											}
										}));
								
							}else{
								//本地没数据
							}
							
//							Intent intent=new Intent(FreshConstants.ADD_SERVER_SHOPPINGCAR);
//							intent.putExtra("list", (Serializable)listmap_serve);
//							sendBroadcast(intent);
						} else {
							
						}
					}

				}, new Response.ErrorListener() {

					public void onErrorResponse(VolleyError arg0) {
						// dialog.dismiss();
						Toast.makeText(LoginActivity.this, "获取失败", 1).show();
						progressDialog.dismiss();
					}
				}));
	}

	/**
	 * 
	 * @Description 获取用户头像
	 * @param 说明参数含义
	 * @return 说明返回值含义
	 */
	private void getCustomerInfo(final String userId, final String token) {
		// TODO Auto-generated method stub
		Map<String, String> params = new HashMap<String, String>();
		params.put("customerid", userId);
		params.put("token", token);

		executeRequest(new StringRequest(UrlConstants.getCustomerInfo, params,
				new Response.Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						Log.e("用户信息是多少………………", arg0);
						if (Utils.parseJsonStr(arg0).get("result").toString()
								.equals("1")) {
							Map<String, Object> map = (Map<String, Object>) Utils
									.parseJsonStr(arg0).get("data");
							String birthday = map.get("birthday").toString();
							String headUrl = map.get("head_url").toString();
							String sex = map.get("sex").toString();

							SharedPreferences userShared = FreshConstants
									.getUserShared(LoginActivity.this);
							Editor editor = userShared.edit();
							editor.putString("birthday", birthday);
							editor.putString("headUrl", headUrl);
							editor.putString("sex", sex);
							editor.commit();

						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						Toast.makeText(LoginActivity.this, "获取失败", 1).show();
						progressDialog.dismiss();
					}
				}));
	}
	
	public Cursor getAllPersonInfo() {
		return DBManager.getDBconnection(LoginActivity.this).query("fresh_shoppingcar", new String[] {"product_id", "picurl", "name", "stock","price","count" }, null, null, null, null, null);
	}
	public List<Map<String,Object>> queryAllLocal(){
		List<Map<String,Object>> listmap_local=new ArrayList<Map<String,Object>>();
		Cursor cursor=getAllPersonInfo();
		int totalprice=0;
		 if (cursor.moveToFirst() == true)  
         {  
             String str = "";  
               
             for (int index=0; index<cursor.getCount(); index++)  
             {  
            	 Map<String,Object> map=new HashMap<String, Object>();
            	 String product_id = cursor.getString(cursor.getColumnIndex("product_id"));  
                 String picurl = cursor.getString(cursor.getColumnIndex("picurl"));  
                 String name = cursor.getString(cursor.getColumnIndex("name"));  
                 String stock = cursor.getString(cursor.getColumnIndex("stock"));  
                 String price = cursor.getString(cursor.getColumnIndex("price"));  
                 String count = cursor.getString(cursor.getColumnIndex("count"));  
                 map.put("product_id", product_id);
                 map.put("picurl", picurl);
                 map.put("name", name);
                 map.put("stock", stock);
                 map.put("price", price);
                 map.put("count", count);
                 listmap_local.add(map);
                 
                 //计算价格 数量*单价
//                 float count=Float.parseS(count);
                 float mycount=Float.parseFloat(count);
                 float myprice=Float.parseFloat(price);
                 totalprice+=mycount*myprice;
                 cursor.moveToNext();  
             }  
             cursor.close();  
               
         }  
         else  
         {  
        	 totalprice=0;
        	 
         }  
		return listmap_local;
	}
}
